#!/bin/usr/python
#encoding=utf8

#----------------------------------
#   author   : albertcheng
#   date     : 2012-10-28
#   file     : dbo.py
#---------------------------------- 
    
import wx
import string
from request_handler import request_sqlite
from log import Log
import re

class CharValidator(wx.PyValidator):
    def __init__(self, flag):
        
        wx.PyValidator.__init__(self)
        self.flag = flag
        self.Bind(wx.EVT_CHAR, self.OnChar)

    def Clone(self):
        """
        Note that every validator must implement the Clone() method.
        """
        return CharValidator(self.flag)

    def Validate(self, win):
        return True

    def TransferToWindow(self):
        return True 

    def TransferFromWindow(self):
        return True

    def OnChar(self, evt):
        key = chr(evt.GetKeyCode())
        if self.flag == "no-alpha" and key in string.letters:
            return
        if self.flag == "no-digit" and key in string.digits:
            return
        if self.flag == "ip" and (key not in string.digits and key != "."):
            return 
        evt.Skip()
        
        

    
class DBConfigDialog(wx.Dialog):
    def __init__(self):
        
        wx.Dialog.__init__(self, None, -1, "Mysql参数配置管理".decode("utf-8"), style=wx.CAPTION|wx.CLOSE_BOX)
        self.Log = Log()
        
        self.sqlite_request = request_sqlite(self.Log)
        # Create the text controls
        about   = wx.StaticText(self, -1, "欢迎使用离子战锤工作室的mysql工具".decode("utf-8"))
        choose_l = wx.StaticText(self,-1,"mysql链接方案选择".decode("utf-8"))
        
        host_l  = wx.StaticText(self, -1, "host:")
        port_l = wx.StaticText(self, -1, "port:")
        user_l = wx.StaticText(self, -1, "user:")
        passwd_l = wx.StaticText(self, -1, "passwd:")
        charset_l = wx.StaticText(self, -1, "charset:")

        
        self.choose_c = wx.Choice(self, -1, (85, 18), choices=[]) 
        
    
        self.host_t  = wx.TextCtrl(self, validator=CharValidator("no-alpha"))
        self.port_t = wx.TextCtrl(self, validator=CharValidator("no-alpha"))
        self.user_t = wx.TextCtrl(self, validator=CharValidator("any"))
        self.passwd_t = wx.TextCtrl(self, validator=CharValidator("any"))
        self.charset_t = wx.TextCtrl(self, validator=CharValidator("any"))
        

        
        # Use standard button IDs
        
        addnew  = wx.Button(self, wx.ID_NEW,"增加".decode("utf-8"))
        #addnew.SetDefault()
        okay   = wx.Button(self, wx.ID_OK,"保存并使用".decode("utf-8"))
        #okay.SetDefault()
        delete = wx.Button(self, wx.ID_DELETE,"删除".decode("utf-8"))

        # Layout with sizers
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(about, 0, wx.ALL, 5)
        sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)
        
        
        fgs = wx.FlexGridSizer(11, 2, 5, 5)
        fgs.Add(choose_l,0,wx.ALIGN_RIGHT)
        fgs.Add(self.choose_c,0,wx.EXPAND)
        fgs.Add(host_l, 0, wx.ALIGN_RIGHT)
        fgs.Add(self.host_t, 0, wx.EXPAND)
        fgs.Add(port_l, 0, wx.ALIGN_RIGHT)
        fgs.Add(self.port_t, 0, wx.EXPAND)
        fgs.Add(user_l, 0, wx.ALIGN_RIGHT)
        fgs.Add(self.user_t, 0, wx.EXPAND)
        fgs.Add(passwd_l, 0, wx.ALIGN_RIGHT)
        fgs.Add(self.passwd_t, 0, wx.EXPAND)     
        fgs.Add(charset_l, 0, wx.ALIGN_RIGHT)
        fgs.Add(self.charset_t, 0, wx.EXPAND)             
               
        fgs.AddGrowableCol(1)
        sizer.Add(fgs, 0, wx.EXPAND|wx.ALL, 5)
        sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)
        
        btns = wx.BoxSizer(wx.HORIZONTAL)
        btns.Add(addnew,0,1)
        btns.Add(okay,0,1)
        btns.Add(delete,0,1)
        
        sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)

        self.Bind(wx.EVT_BUTTON, self.OnOkay, okay)
        self.Bind(wx.EVT_BUTTON, self.OnAdd, addnew)
        self.Bind(wx.EVT_BUTTON, self.OnDel, delete)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        #=======================================================================
        # get db config data from sqlite3 
        #=======================================================================
        self.loaddata()
        
        self.SetSizer(sizer)
        sizer.Fit(self)
        self.Bind(wx.EVT_CHOICE, self.EvtChoice, self.choose_c)
        
        self.Centre()
        
    def EvtChoice(self,e):
        
        self.cfg_db = self.sqlite_request.get()[0]
        self.select_id = e.GetSelection()
        self.ch_data = self.cfg_db[self.select_id]
        print "self.ch_data",self.ch_data
        
        host = self.ch_data[2]
        port = str(self.ch_data[3])
        user = self.ch_data[4]
        passwd = self.ch_data[5]
        charset = self.ch_data[6]
        self.host_t.SetValue(host)
        self.port_t.SetValue(port)
        self.user_t.SetValue(user)
        self.passwd_t.SetValue(passwd)
        self.charset_t.SetValue(charset)
        
        
    def Getdata(self):
        
        self.cfg =  self.sqlite_request.get()
        self.cfg_prefer = self.cfg[1]
        self.cfg_db = self.cfg[0]
        if self.cfg_db != []:
            self.ips = [x[2] for x in self.cfg_db]
            flag = False
            m = 0
            for n in self.cfg_db:
                m+=1
                if n[1] == 1:
                    self.ch_data = n
                    ch_id   = n[0]
                    self.idx = m
                    flag = True
            if not flag:
                self.idx = 0
                self.ch_data = self.cfg_db[0]
                ch_id = self.cfg_db[0][0]
                
            self.select_id = ch_id
        else:
            self.ch_data = ["","","","","","",""]      
            self.ips = []
            self.idx = 0
            self.select_id = 0
    
    def loaddata(self):
        self.Getdata() # refreshing globe data in this class.
        
        host = self.ch_data[2]
        port = str(self.ch_data[3])
        user = self.ch_data[4]
        passwd = self.ch_data[5]
        charset = self.ch_data[6]
        
        
        self.choose_c.SetItems(self.ips)
        self.choose_c.SetSelection(self.idx)
        
        self.host_t.SetValue(host)
        self.port_t.SetValue(port)
        self.user_t.SetValue(user)
        self.passwd_t.SetValue(passwd)
        self.charset_t.SetValue(charset)
        
        
    def OnClose(self,e):
        self.Destroy()
        
        
    def OnOkay(self,e):
        
        self.Getdata()
        nid = self.choose_c.GetSelection()
        
        self.ch_data = self.cfg_db[nid]
        self.select_id = self.ch_data[0]
        
        host = self.host_t.GetValue().strip()
        port = self.port_t.GetValue().strip()
        user = self.user_t.GetValue().strip()
        passwd = self.passwd_t.GetValue().strip()
        charset = self.charset_t.GetValue().strip()
        ip = re.findall(r"\d+\.\d+\.\d+\.\d+",host)
        if ip == []:
            wx.MessageBox("Not a validated Host name!\nYou must input a correct IP addresss!",'Notice',wx.OK)
            return
        if port == "":
            port = 3306
        if user == "":
            user = "root"
        if passwd == "":
            passwd = "123456"
        if charset == "":
            charset = "utf8"
        print self.select_id
        self.sqlite_request.save(self.select_id,host, port, user, passwd, charset)
        wx.MessageBox("Data saved sussefully.",'Notice',wx.OK)
        self.Destroy()
        return 2
        
    def OnAdd(self,e):
        host = self.host_t.GetValue().strip()
        port = self.port_t.GetValue().strip()
        user = self.user_t.GetValue().strip()
        passwd = self.passwd_t.GetValue().strip()
        charset = self.charset_t.GetValue().strip()
        ip = re.findall(r"\d+\.\d+\.\d+\.\d+",host)
        
        if ip == []:
            wx.MessageBox("Not a validated Host name!\nYou must input a correct IP addresss!",'Notice',wx.OK)
            return
        if port == "":
            port = 3306
        if user == "":
            user = "root"
        if passwd == "":
            passwd = "123456"
        if charset == "":
            charset = "utf8"
        
        self.sqlite_request.add(host, port, user, passwd, charset)
        self.loaddata()
        wx.MessageBox("Add New Mysql Connection Plan Successfully.","Notice", wx.OK)
        
        
    def OnDel(self,e):
        self.Getdata()
        nid = self.choose_c.GetSelection()
        
        self.ch_data = self.cfg_db[nid]
        self.select_id = self.ch_data[0]
        
        self.sqlite_request.delete(self.select_id)
        self.loaddata()
        wx.MessageBox("Delete Mysql Connection Plan Successfully.","Notice", wx.OK)